<template>
  <div class="home-container">
    <div class="main-content">
      <div class="header">
        <div class="header-content">
          <h1>{{ currentList ? currentList.name : '我的待办事项' }}</h1>
          <div class="header-actions">
            <button class="add-task-btn" @click="showAddTaskModal = true" v-if="currentListId">
              <i class="fas fa-plus"></i> 添加任务
            </button>
          </div>
        </div>
      </div>

      <div class="tasks-container" v-if="currentListId">
        <div class="tasks-section">
          <h2>待完成</h2>
          <div class="tasks-list">
            <div
              v-for="task in pendingTasks"
              :key="task.id"
              class="task-item"
            >
              <div class="task-status">
                <el-checkbox 
                  :model-value="task.status === 1" 
                  @change="() => toggleTaskStatus(task)"
                  @click.stop
                />
              </div>
              <div class="task-content" @click="editTask(task)">
                <div class="task-title">{{ task.name }}</div>
                <div class="task-description" v-if="task.description">{{ task.description }}</div>
                <div class="task-due-date" v-if="task.dueDate">
                  截止日期: {{ formatDate(task.dueDate) }}
                </div>
              </div>
              <div class="task-actions">
                <el-button 
                  type="danger" 
                  :icon="Delete" 
                  circle 
                  @click="confirmDeleteTask(task)"
                />
              </div>
            </div>
            <div v-if="pendingTasks.length === 0" class="empty-state">
              没有待完成的任务
            </div>
          </div>
        </div>

        <div class="tasks-section">
          <h2>已完成</h2>
          <div class="tasks-list">
            <div
              v-for="task in completedTasks"
              :key="task.id"
              class="task-item completed"
            >
              <div class="task-status">
                <el-checkbox 
                  :model-value="task.status === 1" 
                  @change="() => toggleTaskStatus(task)"
                  @click.stop
                />
              </div>
              <div class="task-content" @click="editTask(task)">
                <div class="task-title">{{ task.name }}</div>
                <div class="task-description" v-if="task.description">{{ task.description }}</div>
                <div class="task-due-date" v-if="task.dueDate">
                  截止日期: {{ formatDate(task.dueDate) }}
                </div>
              </div>
              <div class="task-actions">
                <el-button 
                  type="danger" 
                  :icon="Delete" 
                  circle 
                  @click="confirmDeleteTask(task)"
                />
              </div>
            </div>
            <div v-if="completedTasks.length === 0" class="empty-state">
              没有已完成的任务
            </div>
          </div>
        </div>
      </div>

      <div class="welcome-message" v-else>
        <h2>欢迎使用待办事项应用</h2>
        <p>请从左侧选择一个列表，或者创建一个新的列表来开始</p>
      </div>
    </div>

    <!-- 添加列表模态框 -->
    <div class="modal" v-if="showAddListModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ editingList ? '编辑列表' : '新建列表' }}</h2>
          <button class="close-btn" @click="closeAddListModal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="listName">列表名称</label>
            <input
              type="text"
              id="listName"
              v-model="listForm.name"
              required
              placeholder="请输入列表名称"
            />
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAddListModal">取消</button>
          <button class="save-btn" @click="saveList" :disabled="!listForm.name">保存</button>
        </div>
      </div>
    </div>

    <!-- 添加任务模态框 -->
    <div class="modal" v-if="showAddTaskModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ editingTask ? '编辑任务' : '添加任务' }}</h2>
          <button class="close-btn" @click="closeAddTaskModal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="taskTitle">任务标题</label>
            <input
              type="text"
              id="taskTitle"
              v-model="taskForm.name"
              required
              placeholder="请输入任务标题"
            />
          </div>

          <div class="form-group">
            <label for="taskDescription">任务描述</label>
            <textarea
              id="taskDescription"
              v-model="taskForm.description"
              placeholder="请输入任务描述"
            ></textarea>
          </div>

          <div class="form-group">
            <label for="taskDueDate">截止日期</label>
            <input
              type="date"
              id="taskDueDate"
              v-model="taskForm.dueDate"
            />
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAddTaskModal">取消</button>
          <button class="save-btn" @click="saveTask" :disabled="!taskForm.name">保存</button>
        </div>
      </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal" v-if="showDeleteConfirmModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>确认删除</h2>
          <button class="close-btn" @click="closeDeleteConfirmModal">&times;</button>
        </div>
        <div class="modal-body">
          <p>{{ deleteConfirmMessage }}</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeDeleteConfirmModal">取消</button>
          <button class="delete-btn" @click="confirmDelete">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, onUnmounted } from 'vue';

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};
import { Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/user';
import { useListStore } from '../store/list';
import { useTaskStore } from '../store/task';

const router = useRouter();
const userStore = useUserStore();
const listStore = useListStore();
const taskStore = useTaskStore();

// 用户信息
const currentUser = computed(() => userStore.currentUser);

// 列表相关
const lists = computed(() => listStore.getLists);
const currentListId = computed(() => taskStore.currentListId);
const currentList = computed(() => lists.value?.find(list => list.id === currentListId.value));

// 任务相关
const tasks = computed(() => taskStore.getTasks);
const pendingTasks = computed(() => taskStore.getTasksByStatus(0)); // 0表示pending
const completedTasks = computed(() => taskStore.getTasksByStatus(1)); // 1表示completed

// 模态框状态
const showAddListModal = ref(false);
const showAddTaskModal = ref(false);
const showDeleteConfirmModal = ref(false);

// 表单数据
const listForm = reactive({
  name: ''
});

const taskForm = reactive({
  name: '',
  description: '',
  dueDate: ''
});

// 编辑状态
const editingList = ref(null);
const editingTask = ref(null);

// 删除确认
const deleteType = ref('');
const deleteItem = ref(null);
const deleteConfirmMessage = ref('');

// 生命周期钩子
onMounted(() => {
  // 监听来自Sidebar的显示添加列表模态框事件
  window.addEventListener('show-add-list-modal', () => {
    showAddListModal.value = true;
  });
  
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    router.push('/login');
    return;
  }

  // 获取用户信息
  const fetchUserData = async () => {
    if (!currentUser.value) {
      try {
        await userStore.fetchUserInfo();
      } catch (error) {
        console.error('获取用户信息失败:', error);
        router.push('/login');
        return;
      }
    }
    
    // 获取用户的列表
    try {
      await listStore.fetchLists(currentUser.value.id);

      // 如果有列表数据，默认选择第一个列表
      if (lists.value && lists.value.length > 0 && !currentListId.value) {
        taskStore.setCurrentListId(lists.value[0].id);
      }
    } catch (error) {
      console.error('获取列表失败:', error);
    }
  };
  
  fetchUserData();
});

// 监听当前列表ID变化，加载对应的任务
watch(currentListId, async (newListId) => {
  if (newListId) {
    try {
      await taskStore.fetchTasks(newListId);
    } catch (error) {
      console.error('获取任务失败:', error);
    }
  }
});

// 添加onUnmounted钩子
onUnmounted(() => {
  window.removeEventListener('show-add-list-modal', () => {
    showAddListModal.value = true;
  });
});

// 选择列表
const selectList = (listId) => {
  taskStore.setCurrentListId(listId);
};

// 编辑列表
const editList = (list) => {
  editingList.value = list;
  listForm.name = list.name;
  showAddListModal.value = true;
};

// 确认删除列表
const confirmDeleteList = (list) => {
  deleteType.value = 'list';
  deleteItem.value = list;
  deleteConfirmMessage.value = `确定要删除列表 "${list.name}" 吗？这将同时删除列表中的所有任务！`;
  showDeleteConfirmModal.value = true;
};

// 关闭添加列表模态框
const closeAddListModal = () => {
  showAddListModal.value = false;
  editingList.value = null;
  listForm.name = '';
};

// 保存列表
const saveList = async () => {
  try {
    if (editingList.value) {
      // 更新列表
      await listStore.updateList({
        id: editingList.value.id,
        name: listForm.name
      });
    } else {
      // 创建新列表
      const newList = await listStore.createList({
        name: listForm.name,
        userId: currentUser.value.id
      });

      // 自动选择新创建的列表
      selectList(newList.id);
    }

    closeAddListModal();
  } catch (error) {
    console.error('保存列表失败:', error);
  }
};

// 编辑任务
const editTask = (task) => {
  editingTask.value = task;
  taskForm.name = task.name;
  taskForm.description = task.description || '';

  // 处理日期格式，从LocalDateTime转换为HTML date输入所需的格式
  if (task.dueDate) {
    // 提取日期部分 (YYYY-MM-DD)
    taskForm.dueDate = task.dueDate.split('T')[0];
  } else {
    taskForm.dueDate = '';
  }

  showAddTaskModal.value = true;
};

// 确认删除任务
const confirmDeleteTask = (task) => {
  deleteType.value = 'task';
  deleteItem.value = task;
  deleteConfirmMessage.value = `确定要删除任务 "${task.name}" 吗？`;
  showDeleteConfirmModal.value = true;
};

// 关闭添加任务模态框
const closeAddTaskModal = () => {
  showAddTaskModal.value = false;
  editingTask.value = null;
  taskForm.name = '';
  taskForm.description = '';
  taskForm.dueDate = '';
};

// 保存任务
const saveTask = async () => {
  try {
    const taskData = {
      name: taskForm.name,
      description: taskForm.description,
      dueDate: taskForm.dueDate ? `${taskForm.dueDate}T00:00:00` : null
    };

    if (editingTask.value) {
      // 更新任务
      await taskStore.updateTask({
        id: editingTask.value.id,
        ...taskData
      });
    } else {
      // 创建新任务
      await taskStore.createTask(taskData);
    }

    closeAddTaskModal();
  } catch (error) {
    console.error('保存任务失败:', error);
  }
};

// 切换任务状态
const toggleTaskStatus = async (task) => {
  try {
    const newStatus = task.status === 1 ? 0 : 1; // 1表示completed，0表示pending
    await taskStore.toggleTaskStatus(task.id, newStatus);
    // 手动更新本地状态以确保UI响应
    const index = taskStore.tasks.findIndex(t => t.id === task.id);
    if (index !== -1) {
      taskStore.tasks[index].status = newStatus;
    }
    
    // 如果是从待完成切换到已完成，或者从已完成切换到待完成
    // 重新获取任务列表以确保UI正确更新
    if (currentListId.value) {
      await taskStore.fetchTasks(currentListId.value);
    }
  } catch (error) {
    console.error('更新任务状态失败:', error);
  }
};

// 关闭删除确认模态框
const closeDeleteConfirmModal = () => {
  showDeleteConfirmModal.value = false;
  deleteType.value = '';
  deleteItem.value = null;
  deleteConfirmMessage.value = '';
};

// 确认删除
const confirmDelete = async () => {
  try {
    if (deleteType.value === 'list') {
      await listStore.removeList(deleteItem.value.id);

      // 如果删除的是当前选中的列表，清除当前列表ID
      if (currentListId.value === deleteItem.value.id) {
        taskStore.setCurrentListId(null);
      }
    } else if (deleteType.value === 'task') {
      await taskStore.removeTask(deleteItem.value.id);
    }

    closeDeleteConfirmModal();
  } catch (error) {
    console.error('删除失败:', error);
  }
};
</script>

<style scoped src="@/assets/home.css"></style>
